import { Controller, Get, Post, Body, Param, Delete, Logger, Res, Session, Headers } from '@nestjs/common';
import { UserService } from './user.service';
import { Result } from 'src/utils/Result';
import { ApiBody, ApiExtraModels, ApiOperation, ApiParam, ApiTags } from '@nestjs/swagger';
import { SvgCaptcha } from 'src/utils/svg.captcha';
import JWT from 'src/utils/jwt';
import { User } from './entities/user.entity';
import { UpdateUserDto } from './dto/update-user.dto';
import { Roles } from 'src/utils/decorator';

@ApiTags('用户模块')
@Controller('user')
export class UserController {
  constructor(private readonly userService: UserService) {}
  @ApiOperation({ description: '获取验证码' })
  @Get('/verify_code')
  getVerifyCode(@Res() res, @Session() session) {
    const Captcha: any = SvgCaptcha.create()
    session.code = Captcha.text;
    res.type('image/svg+xml');
    res.send(Result.success(Captcha.data))
  }
  @ApiOperation({ description: '用户登录' })
  @ApiBody({
    schema: {
      default: {username: '', password: '', code: ''}
    }
  })
  @Post('login')
  async userLogin(@Body() data, @Session() session): Promise<Result> {
    Logger.warn('data' + data.code)
    if (data.code.toLocaleLowerCase() == session.code.toLocaleLowerCase()) {
      const result = await this.userService.userLogin(data)
      if(result) {
        return Result.success(result)
      } else {
        return Result.error('用户名或密码错误', -1)
      }
    } else {
      return Result.error('验证码不正确', -1)
    }
  }  
   
  @Roles('admin', 'common')
  @ApiOperation({ description: '获取所有用户列表' })
  @Post('list')
  async userList(@Body() page: any): Promise<Result> {
    const userList = await this.userService.userList(page)
    return Result.success(userList);
  }
  @ApiOperation({ description: '获取当前登录用户信息' })
  @Get('userInfo')
  async getUserInfo(@Headers('authorization') token) {
    const payload = JWT.verify(token);
    const user: User = await this.userService.getUserInfo(payload.id)
    return Result.success(user)
  }
  @ApiOperation({ description: '添加用户' })
  @ApiParam({ name: 'username', required: true, description: '用户名' })
  @ApiParam({ name: 'phone', required: true, description: '手机号' })
  @ApiParam({ name: 'avatar', required: true, description: '头像' })
  @Post('add')
  async addUser(@Body() data): Promise<Result> {
    const result = await this.userService.addUser(data)
    return Result.success(result)
  }
  @ApiOperation({ description: '删除用户' })
  @ApiParam({name: 'user_id', required: true })
  @Delete('remove/:user_id')
  async remove(@Param('user_id') user_id: number) {
    const result = await this.userService.delete(user_id)
    Logger.warn('result', result)
    return Result.success(result)
  }
  @ApiOperation({ description: '修改用户信息' })
  @Post('/update')
  async updateUser(@Body() user: UpdateUserDto) {
    const result = await this.userService.updateUser(user)
    return Result.success(result)
  }
}
